package com.zxc.behavior.service.Impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dto.LikeBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import com.zxc.behavior.service.ApLikeBehaviorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.heima.common.constants.BehaviorConstants.LIKE_BEHAVIOR;
import static com.heima.common.constants.HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC;

@Service
@Slf4j
public class ApLikeBehaviorServiceImpl implements ApLikeBehaviorService {

    @Resource
    private CacheService cacheService;
    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    @Override
    public ResponseResult Like(LikeBehaviorDto dto) {

        if (dto.getArticleId() == null || checkDate(dto))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        updateArticleMess.setArticleId(dto.getArticleId());
        updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
        if (dto.getOperation() == 0) {
            Object o = cacheService.hGet(LIKE_BEHAVIOR + dto.getArticleId(), user.getId().toString());
            if (o != null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已经点赞了");
            }
            log.info("保存当前key:{} ,{}, {}", dto.getArticleId(), user.getId(), dto);
            cacheService.hPut(LIKE_BEHAVIOR + dto.getArticleId(), user.getId().toString(), JSON.toJSONString(dto));
            updateArticleMess.setAdd(1);
        } else {
            log.info("删除当前key:{} ,{}", dto.getArticleId(), user.getId());
            cacheService.hDelete(LIKE_BEHAVIOR + dto.getArticleId(), user.getId().toString());
            updateArticleMess.setAdd(-1);
        }
        kafkaTemplate.send(HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(updateArticleMess));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private boolean checkDate(LikeBehaviorDto dto) {
        return dto.getType() > 2 || dto.getType() < 0 || dto.getOperation() > 1 || dto.getOperation() < 0;
    }
}
